import pandas as pd
import sys
import time

def main():
    start_time = time.time()
    
    try:
        # 读取两个CSV文件
        print("正在读取rms.csv文件...")
        rms_data = pd.read_csv('rms.csv')
        print(f"成功读取rms.csv，包含 {len(rms_data)} 行数据")
        
        print("正在读取processed_output.csv文件...")
        processed_data = pd.read_csv('processed_output.csv')
        print(f"成功读取processed_output.csv，包含 {len(processed_data)} 行数据")
        
        # 创建一个字典来存储NUM对应的ASA和ZSA值
        rms_dict = dict(zip(rms_data['NUM'], zip(rms_data['ASA'], rms_data['ZSA'])))
        max_num = max(rms_data['NUM'])
        print(f"已创建查找字典，最大接收点编号为 {max_num}")
        
        # 检查是否有接收点编号超出rms.csv中的范围
        max_receiver_point = processed_data['receiver_point'].max()
        if max_receiver_point > max_num:
            print(f"警告：processed_output.csv中存在接收点编号 {max_receiver_point}，超出了rms.csv中的最大编号 {max_num}")
        
        # 更高效的方法：使用映射而不是循环
        print("正在合并数据...")
        processed_data['receiver_point_key'] = processed_data['receiver_point']
        
        # 创建映射DataFrame
        mapping_df = pd.DataFrame({
            'receiver_point_key': rms_data['NUM'],
            'ASA': rms_data['ASA'],
            'ZSA': rms_data['ZSA']
        })
        
        # 使用merge来合并数据
        merged_data = pd.merge(
            processed_data, 
            mapping_df, 
            on='receiver_point_key', 
            how='left'
        )
        
        # 删除临时列
        merged_data = merged_data.drop('receiver_point_key', axis=1)
        
        # 检查是否有缺失值
        missing_count = merged_data['ASA'].isna().sum()
        if missing_count > 0:
            print(f"警告：合并后有 {missing_count} 行缺少ASA/ZSA值")
        
        # 保存合并后的结果
        print("正在保存合并结果...")
        merged_data.to_csv('merged_output.csv', index=False)
        
        end_time = time.time()
        print(f"文件合并完成，结果已保存为 merged_output.csv")
        print(f"处理时间：{end_time - start_time:.2f} 秒")
        
    except FileNotFoundError as e:
        print(f"错误：找不到文件 - {e}")
        return 1
    except pd.errors.EmptyDataError:
        print("错误：文件为空或格式不正确")
        return 1
    except Exception as e:
        print(f"发生错误：{e}")
        return 1
    
    return 0

if __name__ == "__main__":
    sys.exit(main()) 